﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Persistencia
{
    public class TransaccionCache : TransaccionBase
    {
        private static TransaccionCache tran;
        private Dictionary<String, List<HashTableNCSensitive>> sqls= new Dictionary<string,List<HashTableNCSensitive>>();

        private TransaccionCache()
            : base("Cache")
        {
        }

        public static TransaccionCache Transaccion
        {
            get
            {
                if (tran == null)
                    tran = new TransaccionCache();

                return tran;
            }
        }

        public override string Nombre
        {
            get
            {
                return "Cache";
            }
        }

        public override SqlConnection Conexion
        {
            get
            {
                return null;
            }
        }

        public override void Cerrar()
        {
            base.Cerrar();
        }

        private string ToKey(string command, SqlParameterCollection parameters)
        {
            string key = command;
            foreach (SqlParameter parameter in parameters)
                command += "|" + parameter.ParameterName + "|" + parameter.Value;

            return command;
        }

        public override List<HashTableNCSensitive> EjecutarComando(SqlCommand comm, int cantidad)
        {
            string key = ToKey(comm.CommandText, comm.Parameters);
            if (!sqls.ContainsKey(key))
            {
                List<HashTableNCSensitive> resultado=base.EjecutarComando(comm, cantidad);
                sqls.Add(key,resultado);
            }

            return sqls[key];
        }

        internal void Refrescar(Factoria factoriaAActualizar)
        {
            if (factorias.ContainsKey(factoriaAActualizar.GetType().Name))
                ((Factoria)factorias[factoriaAActualizar.GetType().Name]).Refrescar(factoriaAActualizar);
            
        }

        internal override SqlTransaction SQLTran
        {
            get { return null; }
        }
    }
}
